package com.its.controller;

import com.its.domain.BaseResult;
import com.its.utils.FileUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class UploadController {

    @Autowired
    private FileUploadUtils fileUploadUtils;

    // 上传文件
    @PostMapping("/uploadImage")
    public BaseResult upload(@RequestParam("file") MultipartFile file) throws IOException {
        String oldName = file.getOriginalFilename();
        if (oldName == null) {
            return BaseResult.ok("文件名为空");
        }
        String suffix = oldName.substring(oldName.lastIndexOf("."));
        String newName = UUID.randomUUID() + suffix;
        String previewUrl = fileUploadUtils.uploadFile(newName, file.getInputStream());
        return BaseResult.ok(previewUrl);
    }

    // 删除文件
    @DeleteMapping("/delete")
    public BaseResult delete(@RequestParam("filePath") String filePath) {
        fileUploadUtils.deleteFile(filePath);
        return BaseResult.ok("文件已删除");
    }
}
